import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

/**
 * Socket客户端
 */
public class Client {

}

    /**
     * 写入到通道的线程
     */
class writer {
    @SuppressWarnings("unused")
    private Socket socket;
    private PrintWriter printWriter;
    private String str = null;

    public writer(Socket socket) throws IOException {
        this.socket = socket;
        this.printWriter = new PrintWriter(socket.getOutputStream());
    }

        /**
         *向服务端发送指令的方法
         * @param s 要向服务端发送的字符串
         */
    public void send(String s) {
        str = s;
        System.out.println("我说："+str);
        printWriter.write(str + "\r\n");
        printWriter.flush();
    }
}

/**
 * 从通道中读取的线程
  */

class read extends Thread {
    private Socket socket;
    private BufferedReader bufferedReader;
    private String str = null;

    public read(Socket socket) throws IOException {
        this.socket = socket;
        this.bufferedReader = new BufferedReader(new InputStreamReader(socket
                .getInputStream()));
    }

    @Override
    public void run() {
        while (true) {
            try {
                str = bufferedReader.readLine();
                System.out.println("receive:"+str);
                OpJudge(str);
            } catch (IOException e) {
                System.out.println(e.getMessage());
                if(e.getMessage().equals("Connection reset")){
                    new NoBorderDialog("对方掉线 游戏结束");
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    }catch (InterruptedException interruptedException){
                        interruptedException.printStackTrace();
                    }
                    System.exit(-1);
                }
            }
        }
    }

    /**
     * 根据服务端发送来的指令进行对应操作的方法
     * @param msg 服务端发送来的指令<br>
     * msg的几种情况：<br>
     * Already对方准备完毕<br>
     * First我方先手出牌<br>
     * Second我方后手出牌<br>
     * LibraryIndex牌的顺序
     * put对方出牌
     * Pass对方过回合
     * Win/Lose/Equal 己方胜利/失败/平局
     * Settlement 对方申请结算
     */
    private void OpJudge(String msg){
        String[] op = msg.split(" ");
        switch (op[0]){
            case "Already":
            MainFrame.setIsReady(true);
            break;
            case "First":
                TurnManager.Instance.setLocked(false);//先手则开锁
                WhoTurn.Instance.setVisable(true);
                WhoTurn.Instance.ChangeTextToMe();
                break;
            case"Second":
                TurnManager.Instance.setLocked(true);//后手则上锁
                TurnManager.setIsFirstTurn(false);//后手则不是首回合
                DominoManager.Instance.setNowIndex(7);
                WhoTurn.Instance.setVisable(true);
                WhoTurn.Instance.ChangeTextToRival();
                break;
            case"LibraryIndex":
                IndexMsgOperation(msg);
                break;
            case"put"://Example:  put 00 Tail
                //new NoBorderDialog("You Turn");
                TurnManager.Instance.setLocked(false);
                RivalActionJlabel.setRivalAction("打出 "+op[1]);
                WhoTurn.Instance.ChangeTextToMe();
                if(op[2].equals("Tail")){
                    GamePanel.Instance.isFollowTail = true;
                    GamePanel.Instance.isFollowHead = false;
                }else if(op[2].equals("Head")){
                    GamePanel.Instance.isFollowTail = false;
                    GamePanel.Instance.isFollowHead = true;
                }
                //GamePanel.Instance.Judge();
                TurnManager.setRivalPassLastTurn(false);//对方非过牌，刷新
                Dominoes tmp = DominoManager.Instance.DominoInstantiate(op[1]);
                GamePanel.Instance.Judge(tmp);
                GamePanel.Instance.PutDominoes(tmp,false);//打牌
                RivalLibrary.Instance.RemoveOne();
                break;
            case "Pass":
                TurnManager.setRivalPassLastTurn(true);
                TurnManager.Instance.setLocked(false);
                RivalActionJlabel.setRivalAction("过");
                WhoTurn.Instance.ChangeTextToMe();
                break;
            case "Win":
                TurnManager.isOver = true;
                WhoTurn.Instance.YouWin();
                break;
            case "Lose":
                TurnManager.isOver = true;
                WhoTurn.Instance.YouLose();
                break;
            case "Settlement":
                TurnManager.isOver = true;
                int RivalPoint = Integer.parseInt(op[1]);
                int MyPoint = MyLibrary.Instance.CalePoints();
                System.out.println("Rival:"+RivalPoint+" My:"+MyPoint);
                if(MyPoint > RivalPoint){
                    MainFrame.MyWriter.send("Win");
                    WhoTurn.Instance.YouLose();
                }else if(MyPoint <RivalPoint){
                    MainFrame.MyWriter.send("Lose");
                    WhoTurn.Instance.YouWin();
                }else{
                    WhoTurn.Instance.Equal();
                    MainFrame.MyWriter.send("Equal");
                }
                break;
            case"Equal":
                WhoTurn.Instance.Equal();
                break;
            default:
        }
    }

    /**
     * 将牌序字符串转换为数组并赋值给本地的牌序数组
     * @param s 服务端传过来的排序
     */
    private static void IndexMsgOperation(String s){
        int[] array = new int[28];
        String[] tmp = s.split(" ");
        //拆分指令
        ArrayList<Integer> arrayList = new ArrayList<>();
        //指令首句为标识Shuffle
        for(int i = 1;i < tmp.length;i++){
            arrayList.add(Integer.valueOf(tmp[i]));
        }
        //向数组赋值
        for(int i = 0;i < 28;i++){
            array[i] = arrayList.get(i);
        }
        DominoManager.Instance.setLibraryIndex(array);
    }
}